{% extends 'base.html' %}

{% block extrahead %}
  <script src="/static/js/jquery.ui.widget.js"></script>
  <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
  <script src="/static/js/jquery.iframe-transport.js"></script>
  <!-- The basic File Upload plugin -->
  <script src="/static/js/jquery.fileupload.js"></script>
  <!-- Calculate md5 -->
  <script src="/static/js/spark-md5.js"></script>
{% endblock %}

{% block content %}
    <form method="POST" enctype="multipart/form-data">{% csrf_token %}
        {{ form.as_ul }}
        <button id="id_chunked_upload_submit" type="submit">Upload</button>
    </form>

  <progress id="upload_progress" max="100" value="0" style="display:none;"></progress>
  <div id="messages"></div>

  <script type="text/javascript">
    var md5 = "",
        csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
        form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
    function calculate_md5(file, chunk_size) {
      var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
          chunks = chunks = Math.ceil(file.size / chunk_size),
          current_chunk = 0,
          spark = new SparkMD5.ArrayBuffer();
      function onload(e) {
        spark.append(e.target.result);  // append chunk
        current_chunk++;
        if (current_chunk < chunks) {
          read_next_chunk();
        } else {
          md5 = spark.end();
        }
      };
      function read_next_chunk() {
        var reader = new FileReader();
        reader.onload = onload;
        var start = current_chunk * chunk_size,
            end = Math.min(start + chunk_size, file.size);
        reader.readAsArrayBuffer(slice.call(file, start, end));
      };
      read_next_chunk();
    }

    upload_field_submit = $('#id_chunked_upload_submit');
    upload_field_submit.hide();

    upload_progress = $('#upload_progress');
    upload_progress.show();

    upload_field = $('#id_chunked_upload');
    upload_field.multiple = false;
    upload_field.fileupload({
      url: "{% url 'api_chunked_upload' %}",
      dataType: "json",
      maxChunkSize: 1000000, // Chunks of 1MB
      formData: form_data,
      add: function(e, data) { // Called before starting upload
        messages = $('#messages');
        messages.empty();
        $('<p/>').text('Ready to upload ' + data.files[0].name).appendTo(messages);
        upload_field_submit.show();
        data.context = $('#id_chunked_upload_submit')
                        .click(function () {
                            data.context = $('<p/>').text('Uploading...').replaceAll($(this));
                            // If this is the second file you're uploading we need to remove the
                            // old upload_id and just keep the csrftoken (which is always first).
                            form_data.splice(1);
                            calculate_md5(data.files[0], 1000000);  // Again, chunks of 1MB
                            console.log(data)
                            data.submit();
                        });
      },
      chunkdone: function (e, data) { // Called after uploading each chunk
        if (form_data.length < 2) {
          form_data.push(
            {"name": "upload_id", "value": data.result.upload_id}
          );
        }
        $("#messages").append($('<p>').text(JSON.stringify(data.result)));
        var progress = parseInt(data.loaded / data.total * 100.0, 10);
        $("#upload_progress").val(progress);
      },
      done: function (e, data) { // Called when the file has completely uploaded
        $.ajax({
          type: "POST",
          url: "{% url 'api_chunked_upload_complete' %}",
          data: {
            csrfmiddlewaretoken: csrf,
            upload_id: data.result.upload_id,
            md5: md5
          },
          dataType: "json",
          success: function(data) {
            $("#messages").append($('<p>').text(JSON.stringify(data)));
            document.location = data.location;
          }
        });
      },
    });
  </script>

{% endblock %}
